<?php
namespace app\common\model;
use x\Xbase;
class User extends Xbase
{
    
    //pc端_是否登录
    public function isLogin(){
        $token = cookie('token');
        if($token){
            if($this->m=='www'){
                $sql = "select * from user where token=?";
            }else{
                $sql = "select * from user where wap_token=?";
            }
            $rs = $this->db->query($sql,[$token],1);
            return $rs ? $rs : [];
        }
        return [];
    }

    /**
     * pc端_登录
     * @param  [type] $phone [description]
     * @param  [type] $password [description]
     */
  	public function login($phone, $password){
        /* 获取用户数据 */
        $user = $this->db->query('select * from user where phone=?',[$phone],1);
        if (empty($user) || (int)$user['status'] !== 0) {
            $this->setError('用户不存在或被禁用','phone');
            return false;
        }
        if($user['password'] != $this->com_password($password)){
            $this->setError('密码错误','password');
            return false;
        }
        $token = token($user['id']);
        $ip = ip();
        $data = [
            'id' => $user['id'],
            'last_login_ip' => $ip,
            'last_login_time' => time(),
            'login_times' => $user['login_times']+1,
            'update_time' => time(),
        ];
        if($this->m=='www'){
            $type = 0;
            $data['token'] = $token;
        }else{
            $type = 1;
            $data[tokenType()] = $token;
        }
        $this->db->insert('user_login',['user_id'=>$user['id'],'ip'=>$ip,'type'=>$type]);
        $this->db->update('user',$data);
        cookie('token',$token);
        return $token;
  	}

    /**
     * pc端_注册
     * [register description]
     * @param  [type] $username  [description]
     * @param  [type] $userphone [description]
     * @param  [type] $password  [description]
     * @return [type]            [description]
     */
    public function register($username, $userphone,$password){
        /* 获取用户数据 */
        $user = $this->db->query('select * from user where username=?',[$username],1);
        if ($user) {
            $this->setError('用户已存在','username');
            return false;
        }
        /* 获取用户数据 */
        $user = $this->db->query('select * from user where phone=?',[$userphone],1);
        if ($user) {
            $this->setError('该手机号已注册','username');
            return false;
        }
        //$salt = rand(1000,9999);
        $data = [
            'username' => $username,
            'password' => $this->com_password($password),
            'phone' => $userphone,
            'reg_ip' => ip(),
            //'salt' => $salt,
            'create_time' => time(),
            'sex' => 1
        ];
        $this->db->insert('user',$data);
        return true;
    }

    /**
     * 统计用户消费总金额， 修改用户等级
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function countLevel($user_id){
        $rs  =$this->db->query("select ifnull(sum(total_money),0) as money from order_goods where user_id = ? and sh_status>=?",[$user_id,1],1);
        foreach (c('type.user_level_money') as $k => $v){
            if($v <= $rs['money']){
                $this->db->update("user",['id'=>$user_id,'level'=>$k]);
                break;
            }
        }
        return true;
    }

    //自动登录
    public function autoLogin($user_id){
        $user = $this->db->find('user',$user_id);
        if (!$user) return $this->setError('自动登陆失败！');
        $token = token($user['id']);
        $ip = ip();
        $data = [
            'id' => $user_id,
            'last_login_ip' => $ip,
            'last_login_time' => time(),
            'login_times' => $user['login_times']+1,
            'update_time' => time(),
        ];
        if(!$user[tokenType()]){
            $data[tokenType()] = $token;
        }
        $this->db->update('user',$data);
        return $this->db->find('user',$user_id);
    }

    /**
     * 获取上级 每个级别第一个
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function myfirstfather($user_id){
        $user = $this->db->find('user',$user_id,'id,s_tree,level');
        $tree = array_reverse(array_filter(explode(',',$user['s_tree'])));
        if (!$tree) return [];

        $map = [];
        $map[] = ['and','id','in',$tree];
        $w = where($map);
        $rs = $this->db->query("select id,level,name,vip_nums from user {$w[0]}",$w[1]);

        //级别
        $temp = [
            1=>0,
            2=>0,
            3=>0,
            4=>0,
        ];
        $cur_level = $user['level'];
        foreach($tree as $id){
            $cur_info = []; #当前树id的用户信息
            foreach($rs as $val){
                if($val['id']==$id){
                    $cur_info = $val;
                    break;
                }
            }
            if($cur_info['level']>=$cur_level){
                $temp[$cur_info['level']] = $cur_info;
                $cur_level = $cur_info['level']+1;
            }
        }
        return $temp;
    }

    /**
     * 获取下级
     * @param  [type] $user_id [description]
     * @param  [type] $level   [获取下级级别]
     * @return [type]          [description]
     */
    public function myson($user_id,$level=[]){
        $user = $this->db->find('user',$user_id,'id,s_tree,s_id,s_level');
        $s_tree = $user['s_tree'].$user['id'].',';
        $map = [];
        $map[] = ['and','s_tree','like',$s_tree.'%'];
        if ($level) {
            $map[] = ['and','level','in',$level];
        }
        $w = where($map);
        $rs = $this->db->query("select id,level,name from user {$w[0]} order by level desc",$w[1]);
        $temp = [
            'user_ids' => [],
            'user_name' => [],
            'user_level' => [],
        ];
        foreach ($rs as $v) {
            $temp['user_ids'][] = $v['id'];
            if(!$temp['user_level'][$v['level']]) $temp['user_level'][$v['level']] = [];
            $temp['user_level'][$v['level']][] = $v;
            if (!$temp['user_name'][$v['id']]) $temp['user_name'][$v['id']] = "";
            $temp['user_name'][$v['id']] = $v['name'];
        }
        return $temp;
    }


    /**
     * 重置密码
     * [forget description]
     * @param  [type] $phone [description]
     * @param  [type] $password  [description]
     * @return [type]            [description]
     */
    public function forget($phone,$password){
        /* 获取用户数据 */
        $user = $this->db->query('select * from user where phone=?',[$phone],1);
        if (!$user) return $this->setError('账号不存在','username');

        $data = [
            'password' => $this->com_password($password),
            'update_time' => time()
        ];
        $this->db->update('user',$data,["phone=?",[$phone]]);
        return true;
    }

    //加密方式
    public function com_password($password,$salt=''){
        return md5(md5($password).$salt);
    }
}
    